//
//  BaseNetRequest.m
//  siyanone
//
//  Created by LK-IOS on 2018/3/21.
//  Copyright © 2018年 LK-News. All rights reserved.
//

#import "BaseNetRequest.h"
#import "AFNetworking.h"

@interface BaseNetRequest()


@property (nonatomic, strong)AFHTTPSessionManager *manager;
@property (nonatomic, strong)AFURLSessionManager *postManager;


@end


@implementation BaseNetRequest

-(id)initWithRequestMethod:(NSString *)requestMethod
{
    self=[super init];
    
    if (self) {
        _requestMethod = requestMethod;
        
        
    }
    
    return self;
}


+(void)sessionRequestWithparameters:(NSMutableDictionary *)parameters
                             method:(NSString *)method
                         requstType:(RequestType)type
                   WithSuccessBlock:(void(^)(NSDictionary*resultDict))successBlock
                          failBlock:(void(^)(NSError*error))failBlock
{
    BaseNetRequest * request = [[BaseNetRequest alloc] init];
    [request sessionRequestWithparameters:parameters method:method requstType:type WithSuccessBlock:successBlock failBlock:failBlock];
    
}

//根据请求type拼接url
- (NSString *)requestWithType:(RequestType)type
{
    
    NSMutableString *urlStr = [[NSMutableString alloc] init];
    
    [urlStr appendString:baseUrlHttp];
    
    switch (type) {
        case PostRegister:
            [urlStr appendString:@"/publisher/register"];
            break;
        case PositionInPositon:
            [urlStr appendString:@"/buyRecord/pagesHoldPosition"];
            break;
        case PositionSettlement:
            [urlStr appendString:@"/buyRecord/pagesUnwind"];
            break;
        case Login:
            [urlStr appendString:@"/login"];
            break;
        case GetCodeNumber:
            [urlStr appendString:@"/publisher/sendSms"];
            break;
        case ModifyPassword:
            [urlStr appendString:@"/publisher/modifyPassword"];
            break;
        case GetHomeTopData:
            [urlStr appendString:@"/system/getAppHomeTopData"];
            break;
        case GetHomeSaleData:
            [urlStr appendString:@"/buyRecord/tradeDynamic"];
            break;
        case GetHomeSaleReData:
            [urlStr appendString:@"/stock/stockRecommend"];
            break;
        case AddOptionalStock:
            [urlStr appendString:@"/favoriteStock/addFavoriteStock"];
            break;
        case DeleteOptionalStock:
            [urlStr appendString:@"/favoriteStock/removeFavoriteStock"];
            break;
        case TopOptionalStock:
            [urlStr appendString:@"/favoriteStock/topFavoriteStock"];
            break;
        case GetMarketData:
            [urlStr appendString:@"/system/stockMarketExponent"];
            break;
        case GetOptionalStockList:
            [urlStr appendString:@"/favoriteStock/favoriteStockList"];
            break;
        case GetSettingInformationList:
            [urlStr appendString:@"/publisher/getSettingRemind"];
            break;
        case BindBankCard:
            [urlStr appendString:@"/bindCard/bindBankCard"];
            break;
        case BindBankCardList:
            [urlStr appendString:@"/bindCard/myBankCardList"];
            break;
        case SettingPaymentPassWord:
            [urlStr appendString:@"/publisher/modifyPaymentPassword"];
            break;
        case GetKLineData:
            [urlStr appendString:@"/stock/kLine"];
            break;
        case GetStrategyInfo:
            [urlStr appendString:@"/strategytype/lists"];
            break;
        case BuyStock:
            [urlStr appendFormat:@"/buyRecord/buy"];
            break;
        case FundAccount:
            [urlStr appendFormat:@"/capitalAccount/"];
            break;
        case FundDetails:
            [urlStr appendFormat:@"/capitalFlow/pages"];
            break;
        case GetStockNewMarket:
            [urlStr appendFormat:@"/stock/market"];
            break;
        case UserLogout:
            [urlStr appendFormat:@"/logout"];
            break;
        case CapitalAccountInfo:
            [urlStr appendString:@"/capitalAccount/capitalSta"];
            break;
        case GetProvincesList:
            [urlStr appendString:@"/areainfo/provinces"];
            break;
        case GetCityLists:
            [urlStr appendString:@"/areainfo/children/{parentCode}"];
            break;
        case GetBankList:
            [urlStr appendString:@"/cnaps/lists/{cityCode}"];
            break;
        case PromotionInformation:
            [urlStr appendString:@"/promotion/promotion/base"];
            break;
        case PromotionLists:
            [urlStr appendString:@"/promotion/promotion/userpages"];
            break;
        case GetUerInfo:
            [urlStr appendString:@"/publisher/getCurrent"];
            break;
        case WithdrawCash:
            [urlStr appendString:@"/quickpay/wbcsa"];
            //            urlStr = [NSMutableString stringWithString: @"http://10.0.0.48:8083/quickpay/sdpaycsa"];
            break;
        case GetRechargeBankList:
            [urlStr appendString:@"/cnaps/bankinfo/applists"];
            break;
        case Get2000FreeStrategy:
            [urlStr appendString:@"/strategytype/experience"];
            break;
        case InitPaymentPassword:
            [urlStr appendString:@"/publisher/initPaymentPassword"];
            break;
        case GetNewsListDetail:
            [urlStr appendString:@"/crawler/selectData"];
            break;
        case GetNewsDetail:
            [urlStr appendString:@"/crawler/newsDetail"];
            break;//newsDetail
            //GetCompanyProfile,         //获取公司简介
        case GetCompanyProfile:
            [urlStr appendString:@"/crawler/selectCompanyProfile"];
            break;
        case AlipayForwrad:
            [urlStr appendString:@"/alipay/turnrecharge"];
            break;
        case AllDayNews:
            [urlStr appendString:@"/crawler/informationData"];
            break;
        case WeekNews:
            [urlStr appendString:@"/crawler/importantNews"];
            break;//WeekNewsDetail
        case WeekNewsDetail:
            [urlStr appendString:@"/crawler/dailyReportDetail"];
            break;//WeekNewsDetail
        case PostJpushId:
            [urlStr appendString:@"/publisher/registrationId"];
            break;
        case GetMessageList:
            [urlStr appendString:@"/messaging/pages"];
            break;
        case GetHomeTopListKongKe:
            [urlStr appendString:@"/system/banner/lists"];
            break;
        case GetAppVersion:
            [urlStr appendString:@"/appversion/currentAppVersion"];
            break;
        case GetUnreadMessage:
            [urlStr appendString:@"/messaging/remind"];
            break;
        case PostQuickPayMessage:
            [urlStr appendString:@"/payment/quickpaymessage"];
            break;
        case PostQuickPay:
            [urlStr appendString:@"/payment/quickpay"];
            break;
        case OptionsCycle:
            [urlStr appendString:@"/stockoptiontrade/cyclelists"];
            break;
        case OptionsInPositionReword:
            [urlStr appendString:@"/stockoptiontrade/pagesHoldPosition"];
            break;
        case OptionOutPositionReword:
            [urlStr appendString:@"/stockoptiontrade/pagesUnwind"];
            break;
        case OptionsTrade:
            [urlStr appendString:@"/stockoptiontrade/buy"];
            break;
        case HomeOptionsSaleData:
            [urlStr appendString:@"/stockoptiontrade/tradeDynamic"];
            break;
        case GetSystemNewTime:
            [urlStr appendString:@"/system/serverTime"];
            break;
        case GetJdPay:
            [urlStr appendFormat:@"/quickpay/jdh5"];
            //            urlStr = [NSMutableString stringWithString: @"http://10.0.0.48:8083/quickpay/jdh5"];
            break;
        case GetQQpay:
            [urlStr appendFormat:@"/quickpay/qqh5"];
            //            urlStr = [NSMutableString stringWithString: @"http://10.0.0.48:8083/quickpay/qqh5"];
            break;
        case GetLianLianPayUrl:
            [urlStr appendString:@"/quickpay/wbcsa"];
            //            urlStr = [NSMutableString stringWithFormat:@"%@/quickpay/paypal",baseUrlHttp];
            break;
        case GetRealName:
            [urlStr appendString:@"/realname/"];
            break;
        case PostRealName:
            [urlStr appendString:@"/realname/"];
            break;
        case GetAppVersionInformation:
            [urlStr appendString:@"/appversionupgrade/checkUpgrade"];
            break;
        case GetCardPay:
            [urlStr appendString:@"/quickpay/quickbank"];
            break;
        default:
            break;
    }
    
    return urlStr;
    
}



- (NSString *)requestUrlWithParams:(NSMutableDictionary  *)params urlStr:(NSString *)urlStr
{
    
    if (params == nil) {
        return urlStr;
    }else
    {
        return  [NSString stringWithFormat:@"%@?%@",urlStr,[self bodyStrWithDic:params]];
    }
    
    
}

- (NSString *)bodyStrWithDic:(NSMutableDictionary *)params
{
    NSMutableArray *dparams = [[NSMutableArray alloc] initWithCapacity:params.count];
    for (NSString *key in params) {
        NSString *value= [params valueForKey:key];
        [dparams addObject:[NSString stringWithFormat:@"%@=%@",key,value]];
    }
    NSString *paramString = [dparams componentsJoinedByString:@"&"];
    return paramString;
}


-(NSString *)auth_token
{
    return  [[SYUserDataManger sharedInstance] getUserToken];
}


#pragma mark - 请求方法
- (void)sessionRequestWithparameters:(NSMutableDictionary *)parameter method:(NSString *)method  requstType:(RequestType)type WithSuccessBlock:(void (^)(NSDictionary *))successBlock failBlock:(void (^)(NSError *))failBlock
{

    if ([method isEqualToString:@"GET"]) {
        NSString *url = [self requestUrlWithParams:parameter urlStr:[self requestWithType:type]];
        
        [self.manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//#if DEBUG
//            NSLog(@"====Https Finish=====>%@",task.response.URL);
//            NSLog(@"====Success Result=====>%@",[(NSDictionary *)responseObject descriptionWithLocale:responseObject]);
//#endif
            successBlock(responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//#if DEBUG
//            NSLog(@"====Https Error=====>%@",task.currentRequest.URL);
//            NSLog(@"====Error Result=====>%@",error.userInfo);
//
//#endif
            failBlock(error);
            
//            if ([error.userInfo[@"NSLocalizedDescription"] isEqualToString:@"Request failed: forbidden (403)"] && type != GetHomeTopData) {
//                //解决首页两个请求弹窗问题
//                //没有token 让登录
//                [[NSNotificationCenter defaultCenter] postNotificationName:kNoTokenNoti object:nil];
//            }
            
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
            if (responses.statusCode == 403 && type != GetHomeTopData) {
                //解决首页两个请求弹窗问题
                //没有token 让登录
                [[NSNotificationCenter defaultCenter] postNotificationName:kNoTokenNoti object:nil];
            }
            else if (responses.statusCode == 409 && type != GetHomeTopData) {
                //拉黑
                [[NSNotificationCenter defaultCenter] postNotificationName:kNoTeLaHei object:nil];
            }
            
            
        }];
    }
    else if ([method isEqualToString:@"POST"])
    {
        NSString *url = [self requestWithType:type];
        
        NSData *data = [[self bodyStrWithDic:parameter] dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:method URLString:url parameters:nil error:nil];
        
        request.timeoutInterval =  type == WithdrawCash ? 120 :30;
        [request setHTTPBody:data];
        
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setValue:[self auth_token] forHTTPHeaderField:@"Authorization"];
        [request setValue:@"I" forHTTPHeaderField:@"endType"];
        //终端 I表示IOS，A表示Android，H表示PC
        
        [[self.postManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){
            
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
            
            
            
            if (error != nil && httpResponse.statusCode != 503) {
//#if DEBUG
//                NSLog(@"====Https Error=====>%@",response.URL);
//
//#endif
                failBlock(error);
                
//                if (httpResponse.statusCode == 403 && type != PostJpushId) {
//                    //没有token 让登录
//                    [[NSNotificationCenter defaultCenter] postNotificationName:kNoTokenNoti object:nil];
//                }
                if (httpResponse.statusCode == 403 && type != PostJpushId) {
                    //没有token 让登录
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNoTokenNoti object:nil];
                }
                else if (httpResponse.statusCode == 409 && type != PostJpushId) {
                    //拉黑
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNoTeLaHei object:nil];
                }
            }else{
                successBlock(responseObject);
                
//#if DEBUG
//                NSLog(@"====Https Finish=====>%@",response.URL);
//                NSLog(@"====Success Result=====>%@",[(NSDictionary *)responseObject descriptionWithLocale:responseObject]);
//#endif
            }
        }] resume];
        
    }
}

-(void)sessionRequestWithDictionary:(NSMutableDictionary *)parameter andURLString:(NSString *)urlString andAuthToken:(NSString *)authToken WithSuccessBlock:(void(^)(NSDictionary*resultDict))successBlock failBlock:(void(^)(NSError*error))failBlock
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer=[AFJSONRequestSerializer serializer];//声明请求的参数类型为json类型
    //    NSString *auth_token = [[NSUserDefaults standardUserDefaults] objectForKey:@"authToken"];
    [session.requestSerializer setValue:authToken forHTTPHeaderField:@"Authorization"];
    [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [session.requestSerializer setValue:@"I" forHTTPHeaderField:@"endType"];
    //网络请求超时的时间
    session.requestSerializer.timeoutInterval = 30;
    session.responseSerializer = [AFJSONResponseSerializer serializer];
    session.responseSerializer.acceptableContentTypes=[NSSet setWithObjects: @"text/html",@"text/json", @"application/json", @"text/javascript" ,@"text/plain",nil];
    ((AFJSONResponseSerializer *)session.responseSerializer).removesKeysWithNullValues = YES;
    
    if ([_requestMethod isEqualToString:@"GET"]) {//get请求
        [session GET:urlString parameters:parameter progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //请求成功
            //回调请求数据
            successBlock(responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //错误信息回调
            //错误信息回调
            failBlock(error);
            
        }];
    }else{//POST 方法
        
        [session POST:urlString parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            successBlock(responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failBlock(error);
        }];
    }
}


-(void)sessionRequestWithDictionary:(NSMutableDictionary *)parameter andURLString:(NSString *)urlString andBody:(NSString *)body WithSuccessBlock:(void(^)(NSDictionary*resultDict))successBlock failBlock:(void(^)(NSError*error))failBlock
{
    
    
    NSData *data = [body dataUsingEncoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:self.requestMethod URLString:urlString parameters:nil error:nil];
    
    request.timeoutInterval= 30;
    
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    [request setValue:@"I" forHTTPHeaderField:@"endType"];
    [request setHTTPBody:data];
    
    //    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
    
    responseSerializer.removesKeysWithNullValues = YES;
    
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                 @"text/html",
                                                 @"text/json",
                                                 @"text/javascript",
                                                 @"text/plain",
                                                 @"text/xml",
                                                 nil];
    manager.responseSerializer = responseSerializer;
    
    [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        
        
        
        if (error != nil && httpResponse.statusCode != 503) {
            failBlock(error);
        }else{
            successBlock(responseObject);
            
        }
    }] resume];
}


-(void)sessionWithToken:(NSString *)token RequestWithDictionary:(NSMutableDictionary *)parameter andURLString:(NSString *)urlString andBody:(NSString *)body WithSuccessBlock:(void(^)(NSDictionary*resultDict))successBlock failBlock:(void(^)(NSError*error))failBlock
{
    NSData *data = [body dataUsingEncoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:self.requestMethod URLString:urlString parameters:nil error:nil];
    
    request.timeoutInterval= 30;
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:token forHTTPHeaderField:@"Authorization"];
    [request setValue:@"I" forHTTPHeaderField:@"endType"];
    [request setHTTPBody:data];
    
    //    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
    
    responseSerializer.removesKeysWithNullValues = YES;
    
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                 @"text/html",
                                                 @"text/json",
                                                 @"text/javascript",
                                                 @"text/plain",
                                                 @"text/xml",
                                                 nil];
    manager.responseSerializer = responseSerializer;
    
    
    
    [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){
        
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        
        
        if (error != nil && httpResponse.statusCode != 503) {
            failBlock(error);
        }else{
            successBlock(responseObject);
            
        }
        
        
    }] resume];
    
    
}

#pragma mark - lazy load
-(AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
        _manager.requestSerializer=[AFJSONRequestSerializer serializer];//声明请求的参数类型为json类型
        
        [_manager.requestSerializer setValue:[self auth_token] forHTTPHeaderField:@"Authorization"];
        [_manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [_manager.requestSerializer setValue:@"I" forHTTPHeaderField:@"endType"];
        //终端 I表示IOS，A表示Android，H表示PC
        //网络请求超时的时间
        _manager.requestSerializer.timeoutInterval = 30;
        _manager.responseSerializer = [AFJSONResponseSerializer serializer];
        _manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects: @"text/html",@"text/json", @"application/json", @"text/javascript" ,@"text/plain",nil];
        ((AFJSONResponseSerializer *)_manager.responseSerializer).removesKeysWithNullValues = YES;
        
        
    }
    return _manager;
}

-(AFURLSessionManager *)postManager
{
    
    if (!_postManager) {
        _postManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
        
        responseSerializer.removesKeysWithNullValues = YES;
        
        responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"text/json",
                                                     @"text/javascript",
                                                     @"text/plain",
                                                     @"text/xml",
                                                     nil];
        _postManager.responseSerializer = responseSerializer;
    }
    
    return _postManager;
    
}

@end
